package org.aner.tester.scanner;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.project.MavenProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.parameters.P;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Objects;

/**
 *
 *
 * @author liuheng
 * @version 1.0
 * @date 2020/12/29 16:32
 */
public class ProjectClassLoader {

    private Logger logger = LoggerFactory.getLogger(ProjectClassLoader.class);

    private MavenProject project;

    private String resourcePath;

    private ClassLoader classLoader;

    private ProjectClassLoader() {}

    public void build() {
        try {
            // all class paths
            List<String> classpathElements = project.getCompileClasspathElements();
            classpathElements.add( project.getBuild().getOutputDirectory());
            classpathElements.add( project.getBuild().getTestOutputDirectory());
            classpathElements.add(resourcePath);
            classpathElements.add(project.getBuild().getSourceDirectory());
            // convert to URL array
            URL[] urls = classpathElements.stream().map(ele -> {
                try {
                    return new File(ele).toURI().toURL();
                } catch (MalformedURLException e) {
                    logger.info("{} is malformed URL {}", ele, e.getMessage());
                    return null;
                }
            }).filter(Objects::nonNull).toArray(URL[]::new);
            classLoader = new URLClassLoader(urls, ProjectClassLoader.class.getClassLoader());
        } catch (DependencyResolutionRequiredException e) {
            logger.debug( "Couldn't get the classloader, {}", e.getMessage());
            classLoader = ProjectClassLoader.class.getClassLoader();
        }
    }

    public MavenProject getProject() {
        return project;
    }

    public ProjectClassLoader project(MavenProject project) {
        this.project = project;
        return this;
    }

    public String getResourcePath() {
        return resourcePath;
    }

    public ProjectClassLoader resourcePath(String resourcePath) {
        this.resourcePath = resourcePath;
        return this;
    }

    public ClassLoader getClassLoader(){
        return classLoader;
    }

    public static ProjectClassLoader me() {
        return Holder.projectClassLoader;
    }

    private static class Holder {
        public static final ProjectClassLoader projectClassLoader = new ProjectClassLoader();
    }

}
